package cn.mrlong.aavdemo.textureview;

import android.graphics.ImageFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.view.TextureView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import cn.mrlong.aavdemo.R;

import java.io.IOException;

/**
 * TextureView预览相机
 */
public class TextureViewCameraActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {

    private TextureView textureView;
    private Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_texture_view_camera);
        textureView = findViewById(R.id.textureview);
        textureView.setSurfaceTextureListener(this);
        camera = Camera.open();
        //Camera Preview Callback的YUV常用格式有两种：一个是NV21，一个是YV12。Android一般默认使用YCbCr_420_SP的格式（NV21）。
        Camera.Parameters parameters = camera.getParameters();
        parameters.setPreviewFormat(ImageFormat.NV21);
        camera.setParameters(parameters);
        camera.setPreviewCallback(new Camera.PreviewCallback() {
            @Override
            public void onPreviewFrame(byte[] data, Camera camera) {
                //通过setPreviewCallback方法监听预览的回调：
                //一个音视频文件是由音频和视频组成的，我们可以通过MediaExtractor、MediaMuxer把音频或视频给
                //单独抽取出来，抽取出来的音频和视频能单独播放；
            }
        });
        camera.setDisplayOrientation(90);
    }

    @Override
    public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
        try {
            camera.setPreviewTexture(surface);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
        try {
            camera.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

    }
}